<template>
  <!-- 列表 -->
  <el-table
    v-loading="loading"
    :data="list"
    :stripe="true"
    :show-overflow-tooltip="true"
    :row-style="getRowStyle"
  >
    <!-- 子表的列表 -->
    <el-table-column type="expand">
      <template #default="scope">
        <el-tabs model-value="rentFile">
          <el-tab-pane label="租赁合同档案" name="rentFile">
            <RentFileList :belong-id="scope.row.id" />
          </el-tab-pane>
          <el-tab-pane label="宗地信息" name="land">
            <LandList :landIds="scope.row.landIds" />
          </el-tab-pane>
          <el-tab-pane label="年度收益" name="earnings">
            <EarningsList :rent-id="scope.row.id" />
          </el-tab-pane>
          <el-tab-pane label="承租人信息" name="lessee">
            <LesseeList :rent-id="scope.row.id" />
          </el-tab-pane>
          <el-tab-pane label="租金税费管理" name="taxation">
            <TaxationList :rent-id="scope.row.id" />
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-table-column>
    <el-table-column label="预警天数" align="center" width="120px">
      <template #default="scope">
        {{ calculateOverdueDays(scope.row.nextpayDate) }}
      </template>
    </el-table-column>

    <el-table-column label="租赁合同序号" align="center" prop="id" width="60" />
    <!-- <el-table-column label="续签合同序号" align="center" prop="parentId" /> -->
    <!-- <el-table-column label="流程实例的编号" align="center" prop="processInstanceId" width="80" /> -->
    <el-table-column label="确认结果" width="60px" align="center" prop="status">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
      </template>
    </el-table-column>
    <el-table-column label="有效状态" width="60px" align="center" prop="effective">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.SYS_STATUS" :value="scope.row.effective" />
      </template>
    </el-table-column>
    <!-- <el-table-column label="填报人ID" align="center" prop="proposerId" /> -->
    <el-table-column label="租赁宗地序号" align="center" prop="landIds" width="70">
      <template #default="scope">
        <div v-for="(id, index) in scope.row.landIds.split(',')" :key="index">
          <el-link type="primary" @click="openLandForm('update', id.trim())">
            {{ '查看 ' + id }}
            <span v-if="index < scope.row.landIds.split(',').length - 1">, </span>
          </el-link>
        </div>
      </template>
    </el-table-column>
    <!-- <el-table-column label="所属用户id" align="center" prop="userId" /> -->
    <el-table-column label="合同编号" align="center" prop="contractNo" width="200">
      <template #default="scope">
        <el-link type="primary" @click="openForm('update', scope.row.id)">{{
          scope.row.contractNo
        }}</el-link>
      </template>
    </el-table-column>
    <el-table-column label="出租金额" align="center" prop="rentPrice" />
    <el-table-column label="出租期限" align="center" prop="rentPeriod" />
    <el-table-column
      label="开始时间"
      align="center"
      prop="startTime"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column
      label="结束时间"
      align="center"
      prop="endTime"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column label="出租位置" align="center" prop="rentLocation" />
    <el-table-column label="租赁土地面积" align="center" prop="rentLandarea" />
    <!-- <el-table-column label="租赁建筑面积" align="center" prop="rentBuildingarea" />
      <el-table-column label="出租方式" align="center" prop="rentType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.RENT_TYPE" :value="scope.row.rentType" />
        </template>
      </el-table-column> -->
    <el-table-column
      label="合同签订日期"
      align="center"
      prop="signingDate"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column
      label="约定交款日期"
      align="center"
      prop="payDate"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column
      label="上次交款日期"
      align="center"
      prop="paidDate"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column
      label="下次交款日期"
      align="center"
      prop="nextpayDate"
      :formatter="dateFormatter2"
      width="100px"
    />
    <el-table-column label="交费状态" align="center">
      <template #default="scope">
        <el-tag v-if="isPaid(scope.row.paidDate)" type="success">已交费</el-tag>
        <el-tag v-else type="danger">未交费</el-tag>
      </template>
    </el-table-column>
    <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

    <!-- <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['zszx:rent:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['zszx:rent:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
  </el-table>
  <!-- 分页 -->
  <Pagination
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />

  <!-- 表单弹窗：添加/修改 -->
  <RentForm ref="formRef" @success="getList" />

  <LandForm ref="landFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { RentApi, RentVO } from '@/api/zszx/rent'
import RentForm from '@/views/zszx/rent/RentForm.vue'
import LesseeList from '@/views/zszx/rent/components/LesseeList.vue'
import TaxationList from '@/views/zszx/rent/components/TaxationList.vue'
import EarningsList from '@/views/zszx/rent/components/EarningsList.vue'
import LandList from '@/views/zszx/rent/components/LandList.vue'
import RentFileList from '@/views/zszx/rent/components/RentFileList.vue'
import LandForm from '@/views/zszx/land/LandForm.vue'
/** 添加/修改操作 */
const landFormRef = ref()
const openLandForm = (type: string, id?: number) => {
  landFormRef.value.open(type, id)
}

/** 租赁合同管理 列表 */
defineOptions({ name: 'PayExpire' })

const message = useMessage() // 消息弹窗
const router = useRouter() // 路由
const { t } = useI18n() // 国际化

const days = ref(90)
const loading = ref(true) // 列表的加载中
const list = ref<RentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  parentId: undefined,
  processInstanceId: undefined,
  effective: undefined,
  status: undefined,
  proposerId: undefined,
  landIds: undefined,
  userId: undefined,
  contractNo: undefined,
  rentPrice: undefined,
  rentPeriod: undefined,
  startTime: [],
  endTime: [],
  rentLocation: undefined,
  rentLandarea: [],
  rentBuildingarea: [],
  rentType: undefined,
  signingDate: [],
  payDate: [],
  paidDate: [],
  nextpayDate: [],
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

function isPaid(row) {
  //当前日期等于下次交款日期的所属年相同，则已缴
  if (!row) {
    return false
  }
  if (row.paidDate) {
    let lastPaidYear = new Date(row.paidDate).getFullYear()
    if (lastPaidYear == new Date().getFullYear()) {
      return true
    }
  } else if (row.nextpayDate == null) {
    return true
  } else {
    return false
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // const data = await RentApi.getRentPage(queryParams)
    const data = await RentApi.getPayExpireRentPage(queryParams, days.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RentApi.deleteRent(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RentApi.exportRent(queryParams)
    download.excel(data, '租赁合同管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
function getRowStyle(row) {
  // console.log(row)
  let now = new Date()
  if (row.row.nextpayDate) {
    let nextpayDate = new Date(row.row.nextpayDate)
    let timeDiff = nextpayDate.getTime() - now.getTime() //毫秒
    let days = Math.ceil(timeDiff / (1000 * 3600 * 24)) //天数
    if (days <= 60 && days > 30) {
      return {
        background: row.rowIndex % 2 === 0 ? '#f7f7f7' : '#fff',
        color: '#0c0' //芬黄色
      }
    } else if (days <= 30 && days >= 0) {
      return {
        background: row.rowIndex % 2 === 0 ? '#f7f7f7' : '#fff',
        color: '#ff6600' //芬黄色
      }
    } else if (days < 0) {
      //已超期
      return {
        background: row.rowIndex % 2 === 0 ? '#f7f7f7' : '#fff',
        color: '#ff0000' //红色
      }
    } else if (days > 60) {
      //差得远
      return {
        background: row.rowIndex % 2 === 0 ? '#f7f7f7' : '#fff',
        color: '#7f8c8d' //灰色
      }
    }
  } else {
    return {
      background: row.rowIndex % 2 === 0 ? '#f7f7f7' : '#fff'
    }
  }
}
const calculateOverdueDays = (nextpayDate: string | null) => {
  if (!nextpayDate) return '--'

  const now = new Date()
  const payDateObj = new Date(nextpayDate)
  const timeDiff = payDateObj.getTime() - now.getTime()
  const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))

  return daysDiff >= 0 ? `${daysDiff} 天后到期` : `已超期${Math.abs(daysDiff)} 天`
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
